<template>
  <div class="ma-content-block justify-between p-4">
    <!-- CRUD 组件 -->
    <ma-crud :options="options" :columns="columns" ref="crudRef" @selection-change="setSelectedKeys">
      <template #car_type="{record}">
        <a-tooltip :content="record.car_type  + ' ' + record.car_no">
          <div class="ellipsis">
            {{ record.car_type }} - {{ record.car_no }}
          </div>
        </a-tooltip>
      </template>
      <template #producer="{ record }">
        <a-tooltip :content="record.fzs?.name  + ' ' + record.dzs?.name">
          <div>{{ record.fzs?.name || ''}}{{' - '}}{{record?.dzs?.name || ''}}</div>
        </a-tooltip>
      </template>
      <template #service_type="{ record }">
        <div>{{ record.service_type == 1?'站到站':record.service_type == 2?'站到门':record.service_type == 3?'门到站':record.service_type == 4?'门到门':'' }}</div>
      </template>
      <template #ticket_number="{ record }">
        <a-tooltip :content="record.ticket_numbers">
          <div>{{ record.ticket_numbers }}</div>
        </a-tooltip>
      </template>
      
      <template #tableBeforeButtons>
        <a-button type="primary" @click="handleAdd">新增</a-button>
        <a-button type="primary" @click="handelShowUp">批量新增</a-button>
        <a-button type="primary" @click="onepipeiShow = true">匹配客户</a-button>
        <a-button type="primary" @click="handleQueRenFaHuo">确认发货</a-button>
        <a-button type="primary" @click="handleLedgerRenWu">下发装卸任务</a-button>
      </template>
      <template #operationBeforeExtend="{ record }">
        <a-link @click="handlecaozuoMb(record)">操作面板</a-link>
        <a-link @click="openFile(record.ticket_numbers)" >大票</a-link>
        <a-link @click="openTuoyun(record)" v-if="record.is_compled != 0 ">托运单</a-link>
        <!-- <a-link @click="handleZhangdan(record)" v-if="record.is_compled == 1">账单</a-link> -->
        <a-link @click="handleZhangdan(record)" v-if="record.is_compled != 0 " v-auth="['financial:payOrder:index']">账单</a-link>
        <a-link @click="handleQueRenZhangdan(record)" v-if="(record.cost_order_count != 0 || record.pay_order_count != 0) && record.dept_id != 0" >待确认账单({{ record.pay_order_count }} {{record.cost_order_count}})</a-link>
        <a-link @click="xiafaPeiSong(record)" v-if="record.is_compled == 1 && (record.service_type == 3 || record.service_type == 4)">下发派车单</a-link>
        <a-link @click="handlecopy(record)">复制</a-link>
        <!-- <a-link @click="handleQueRenZhangdan(record)" v-if="record.is_compled == 1">确认账单</a-link>
        <a-link @click="handleZhangdan(record)" v-if="record.is_compled == 1">账单</a-link>
        <a-link @click="xiafaPeiSong(record)" v-if="record.is_compled == 1 && record.send_status != 2">接取派车单</a-link>
        <a-link @click="openTuoyun(record)" >托运单</a-link> -->
      </template>
      <!-- <template #summaryCell="{ record,column }">
        {{ column.dataIndex == 'yundanhao' ? '合计' 
        : column.dataIndex == 'number'? record[column.dataIndex]
        : column.dataIndex == 'hz_weight'? (record[column.dataIndex] - 0).toFixed(3)
        : column.dataIndex == 'bz_weight'? (record[column.dataIndex] - 0).toFixed(3)
        : column.dataIndex == 'jf_weight'? (record[column.dataIndex] - 0).toFixed(3)
        : column.dataIndex == 'cyr_weight'? (record[column.dataIndex] - 0).toFixed(3)
        : ''}}
      </template> -->
      <template #summaryCell="{ record,column }">
        {{ column.dataIndex == 'yundanhao' ? '总计' 
        : column.dataIndex == 'number'? itemTotal?.number
        : column.dataIndex == 'hz_weight'? itemTotal?.hz_weight
        : column.dataIndex == 'bz_weight'? itemTotal?.bz_weight
        : column.dataIndex == 'jf_weight'? itemTotal?.jf_weight
        : column.dataIndex == 'cyr_weight'? itemTotal?.cyr_weight
        : ''}}
      </template>
    </ma-crud>
    
    <!-- 确认账单 -->
    <a-modal :mask-closable="false"  v-model:visible="showBill" title="确认账单" @cancel="showBill = false" :width="1400" :footer="false">
      <bill ref="billRef" v-if="showBill" :item="billData" :type="2" @quxiao="showBill = false" @shuaxin="zhangdanshuaxin"></bill>
    </a-modal>
    <!-- 账单 -->
    <a-drawer v-model:visible="zhangdanShow" :footer="false" :width="1400" >
      <template #title> 账单</template>
      <orderItem v-if="zhangdanShow" :info='itemData' />
    </a-drawer>
    <!-- 接取派车单 -->
    <a-modal :mask-closable="false"  v-model:visible="showPeisong" title="下发派车单" @cancel="showPeisong = false" width="900px" :footer="false">
      <peisongindex v-if="showPeisong" :row="peisongData" :user="user" @shuaxin='handleShuaxin' ></peisongindex>
    </a-modal>
    <!-- 打印托运单 -->
    <a-modal :mask-closable="false" 
			v-model:visible="tuoyunShow"
			width="auto"
			title="打印托运单"
			ok-text="打印"
			:footer="false"
		>
			<tuoyun :row="tuoyunList" :user="user" v-if="tuoyunShow"></tuoyun>
		</a-modal>

    <!-- 新增弹窗 -->
    <a-modal :mask-closable="false"  v-model:visible="addShow" title="新增/编辑" @cancel="addShow = false" :width="1500" :footer="false"  >
      <addindex v-if="addShow" :dept_list="dept_list" :yunshuList="yunshuList.value" :item="addData" :fuwuList="fuwuList.value" :goods_list="goods_list" @succ="handleAddSucc"></addindex>
    </a-modal>
    <!-- 导入 -->
    <a-modal :mask-closable="false"  v-model:visible="showUpload" title="导入Excel" @cancel="handleShow" :width="600" :footer="false">
      <div style="padding: 8px 10px; " v-if="showUpload">
        <a-upload :file-list="fileList" draggable :action="env.VITE_APP_OPEN_PROXY === 'true'
            ? env.VITE_APP_PROXY_PREFIX + '/prediction/manage/importFyBat'
            : env.VITE_APP_BASE_URL + '/prediction/manage/importFyBat'
          " :headers="{ Authorization: `Bearer ${token}` }" :on-before-upload="beforeUpload" :limit="1" :data="{
          }" @success="handleSuccess" />
        <div style="margin-top: 12px; color: #1e80ff">
          <a-popconfirm content="是否下载模版?" @ok="downFromOther">
            <a-link>模板下载</a-link>
          </a-popconfirm>
        </div>
      </div>
    </a-modal>
    <!-- 预览预计导入的数据 -->
    <a-modal :mask-closable="false"  v-model:visible="showYuji" title="确认导入数据" @cancel="handleYujiCel" :width="1400" ok-text="确认导入"
      :footer="false">
      <a-table summary-text="合计" summary :columns="columnsEpor" row-key="id" v-model:selectedKeys="selectedKeys"
        :bordered="{ wrapper: true, cell: true }" :row-selection="{
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false,
        }" :data="yujiList" @selection-change="handleSelChange" :pagination="false">
        <template #remark="{ record, rowIndex }">
          <a-tooltip :content="record.remark">
            <div style="
                color: red;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              ">
              {{ record.remark }}
            </div>
          </a-tooltip>
        </template>
        <template #service_type="{record}">
          <div>{{ record.service_type == 1?'站到站':record.service_type == 2?'站到门':record.service_type == 3?'门到站':record.service_type == 4?'门到门':''}}</div>
        </template>
        <template #transport_type="{record}">
          <div>{{ record.transport_type == 1?'集装箱':record.transport_type == 2?'整车':'批量零散'}}</div>
        </template>
        
        <template #is_empty="{ record, rowIndex }">
          <div v-if="record.transport_type == 1">{{ record.is_empty == 1 ? '空箱' : '重箱' }}</div>
          <div v-else>-</div>
        </template>
        <template #sending_station="{ record, rowIndex }">
          <div>{{ handleSend(record.sending_station) }}</div>
        </template>
        <template #come_address="{ record, rowIndex }">
          <div>{{ handleSend(record.come_address) }}</div>
        </template>
        <template #summary-cell="{ column, record, rowIndex }">
          {{
            column.dataIndex == "dept_name"
              ? "合计"
              : column.dataIndex == "bz_weight"
                ? (record[column.dataIndex] - 0).toFixed(3) + "吨"
                : column.dataIndex == "jf_weight"
                ? (record[column.dataIndex] - 0).toFixed(3) + "吨"
                : column.dataIndex == "hz_weight"
                ? (record[column.dataIndex] - 0).toFixed(3) + "吨"
                : column.dataIndex == "cyr_weight"
                ? (record[column.dataIndex] - 0).toFixed(3) + "吨"
                : column.dataIndex == "number"
                  ? record[column.dataIndex] + "件"
                  :''
          }}
        </template>
      </a-table>
      <div style="display: flex; justify-content: flex-end; margin-top: 2%">
        <a-button type="primary" @click="handleYujiSucc" :loading="yujiloading">确认导入</a-button>
      </div>
    </a-modal>
    <!-- 逐条匹配 -->
    <a-drawer :footer="false" :width="1920" v-model:visible="onepipeiShow" @cancel="handleZhutiaoCel">
      <template #title> 匹配客户（逐条） </template>
      <onepipei v-if="onepipeiShow" :dept_list="dept_list" :yunshuList="yunshuList.value" :fuwuList="fuwuList.value" :goods_list="goods_list" />
    </a-drawer>
    <!-- 操作面板 -->
    <a-drawer :footer="false" :width="800" v-model:visible="visiblecaozuoSL">
      <template #title> 操作面板 </template>
      <caozuoMB ref="crudRefczmb" @handleXiugai="handleXiugai" :czsjData="czsjData" :goods_list="goods_list" :tabs="tabs" v-if="visiblecaozuoSL" />
    </a-drawer>
    <!-- 确认发货 -->
    <a-drawer :footer="false" :width="1700" v-model:visible="sendHuoShow">
      <template #title> 确认发货 </template>
      <sendHuo ref="sendHuoRef"  @succ="handlesendHuoSucc" v-if="sendHuoShow" />
    </a-drawer>
    <!-- 发布装卸任务 -->
    <a-drawer :footer="false" :width="1700" v-model:visible="publishLoadShow">
      <template #title> 发布装卸任务 </template>
      <publishLoad ref="publishLoadRef"  @succ="handlepublishLoadSucc" v-if="publishLoadShow" />
    </a-drawer>

    <a-modal :mask-closable="false" 
			v-model:visible="dpShow"
			title="查看大票"
			:footer="false"
      width="1400px"
		>
    <div v-for="(item,index) in dpUrl" :key="index">
      <a-spin :loading="daShpwloading" tip="请稍等..." dot  style="width:100%">
        <iframe
          ref="myIframe"
          :src="item + '#zoom=100'"
          style="width: 100%; height: 800px; border: none;"
        ></iframe>
      </a-spin>
    </div>
    <div v-if="dpUrl.length == 0" >
      <a-spin :loading="true" tip="请稍等..." dot  style="width:100%">
        <div style="width: 100%; height: 800px; border: none;"></div>
      </a-spin>
    </div>
		</a-modal>

  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import sendManage from '@/api/send/sendManage'
import predictionManage from "@/api/prediction/predictionManage";
import { Message } from '@arco-design/web-vue'
import { Notification } from "@arco-design/web-vue";
import pipeiindex from "@/views/send/manage/pipeiindex.vue";
import addindex from "@/views/send/manage/components/add.vue";
import sendHuo from "@/views/send/manage/components/sendHuo.vue";
import publishLoad from "@/views/send/manage/components/publishLoad.vue";
import peisongindex from "@/views/send/manage/peisong.vue";
import onepipei from "@/views/send/manage/components/onepipei.vue";
import caozuoMB from "@/views/send/manage/components/caozuoMB.vue";
import tuoyun from "./components/tuoyun.vue"
import tool from '@/utils/tool'
import commonApi from "@/api/common";
import { pinyin } from "pinyin-pro"
import { request } from "@/utils/request.js";
import orderItem from "./orderItem.vue"
import { useUserStore } from "@/store";
import bill from "@/components/bill/index.vue"
import * as common from '@/utils/common'
const env = ref(import.meta.env);
const token = ref(tool.local.get(import.meta.env.VITE_APP_TOKEN_PREFIX));
const userStore = useUserStore();
// 当前登录的用户所有信息，包括 id 用户名 昵称 等信息
const user = userStore.user;
const crudRef = ref()
const itemData = ref({})
const addData = ref({
        car_type:'',  // 车种
        car_no:'',  // 车号
        process_time:tool.dateFormat(
          Math.round(new Date().getTime() / 1000).toString(),
          "yyyy-MM-dd hh:mm:ss"
        ),  // 办理时间
        transport_type:'1',  // 运输方式
        service_type:'',  //  服务方式
        shipper:'',   // 托运人
        shipper_agent:'',   // 托运经办人
        shipper_phone:'',   // 托运人电话
        sending_station:'',   // 发站
        sending_tlj:'',   // 发 铁路局
        sending_station_special:'',  // 发站专用线
        come_address:'',   // 到站
        come_tlj:'',   // 到 铁路局
        arrive_station_special:'四川威斯腾物流有限公司专用线',  // 到站专用线
        dept_id:'',   // 客户
        customer_handler:'',   // 客户经办人
        customer_tel:'',    // 客户电话
        contract_id:'',   // 合同
        serve_type:'3',   // 是否仓储
        shipping:'',   // 配送电话
        shipping_address:'',   // 配送地址
        goods_data:[],
})
const billData = ref({})
const czsjData = ref({})
const tabs = ref('jc')
const pipeiindexRef = ref(null)
const sendHuoRef = ref(null)
const publishLoadRef = ref(null)
const sendHuoShow = ref(false)
const publishLoadShow = ref(false)
const showBill = ref(false)
const visiblecaozuoSL = ref(false)
const pipeiShow = ref(false)
const showPeisong = ref(false)
const peisongData = ref({})
const zhangdanShow = ref(false)
const onepipeiShow = ref(false)
const tuoyunShow = ref(false)
const tuoyunList = ref([])
const addObj = ref({})
const addShow = ref(false)
const dept_list = ref([])   //  公司列表
const yunshuList = reactive([]);
const fuwuList = reactive([]);
const goods_list = ref([])  // 商品列表
const selectedKeys = ref([]);
const fileList = reactive([]);
const showUpload = ref(false);
let yujiList = [];
let keys = [];
const showYuji = ref(false);
const yujiloading = ref(false)
const handleAdd = () => {
  console.log('新增')
  addObj.value = {
    box: '',
    box_belong: '',
    box_type_id: '',
    car_no: '',
    car_type:'',
    contract_id: '',
    dept_id: '',
    goods_id: '',
    number_yu: '',
    producer: '',
    serve_type: '',
    transport_type: '',
    come_address:'遂宁南',
    yb_weight: '',
    bz_weight: '',
    hz_weight: '',
    jf_weight: '',
    cyr_weight: '',
    ticket_number:'',
    box: '',
    is_empty: '',
  }
  addData.value = {
        car_type:'',  // 车种
        car_no:'',  // 车号
       
        process_time:tool.dateFormat(
          Math.round(new Date().getTime() / 1000).toString(),
          "yyyy-MM-dd hh:mm:ss"
        ),  // 通知时间
        transport_type:'1',  // 运输方式
        service_type:'',  //  服务方式
        shipper:'',   // 托运人
        shipper_agent:'',   // 托运经办人
        shipper_phone:'',   // 托运人电话
        sending_station:'',   // 发站
        sending_tlj:'',   // 发 铁路局
        sending_station_special:'',  // 发站专用线
        come_address:'',   // 到站
        come_tlj:'',   // 到 铁路局
        arrive_station_special:'四川威斯腾物流有限公司专用线',  // 到站专用线
        dept_id:'',   // 客户
        customer_handler:'',   // 客户经办人
        customer_tel:'',    // 客户电话
        contract_id:'',   // 合同
        serve_type:'3',   // 是否仓储
        shipping:'',   // 配送电话
        shipping_address:'',   // 配送地址
        goods_data:[],
  }
  addShow.value = true
}
const handleDeptList = () => {   //  获取公司列表
  request({
    url: 'system/dept/index',
    method: 'get',
    data: {
      openPage: false,
      remoteOption: {
        filter: {
          type: ['=', 2],
          status: ["=",1]
        },
        select: ["id", "name"],
        sort: { id: "desc" }
      }
    }
  }).then(res => {
    let arr = []
    res.data.map((v,i)=>{
        v.keywords = [
        v.name,
        pinyin(v.name,{toneType:'none',pattern:'first'}).split(' ').join(''),
        pinyin(v.name,{toneType:'none',pattern:'first'}).split(' ').join('').toUpperCase()
        ]
        if(v.status == 1){
        arr.push(v)
        }
    })
    dept_list.value = arr
  })
}
const handlesendHuoSucc = (item)=>{
  Message.success('已确认发货！')
  crudRef.value.refresh();
}
const handleSend = (id)=>{
  let name = ''
  sendList.value.map((v,i)=>{
    if(v.id == id){
      name = v.name
    }
  })
  return name
}

const dpShow = ref(false)
const daShpwloading = ref(false)
const dpUrl = ref([])
const openFile = (id) => {
    // 假设文件URL是http://example.com/file.pdf
    // const fileUrl = 'https://ec.95306.cn/goPdf?aqcnsfileId=' + id;
    let fileUrl = ""
    dpUrl.value = []
    dpShow.value = true
    const queryString = new URLSearchParams({ticket_numbers:id}).toString();
    fetch(`https://pdf.chuangxing.ren/api/index/get_pdf_url?${queryString}`,{
      headers:{
        'Content-Type': 'application/json',
      }
    })
    .then(response => response.json())
    .then(data => {
      if(data.code == 1){
        dpUrl.value = data.data
        daShpwloading.value = true
        setTimeout(() => {
          daShpwloading.value = false
        },1000)
      }else{
        Message.error(data.msg)
        dpShow.value = false
      }
    })
    .catch(error => console.error('Error:', error));
    // let ids = id.split(',')
    // ids.map((v,i)=>{
      
    //   request({
    //       url: `https://pdf.chuangxing.ren/api/index/get_pdf_url`,
    //       method: 'get',
    //       params: {
    //           ticket_numbers: id,
    //       }
    //   }).then(res => {
    //       console.log("res:",res)
    //       // fileUrl = env.value.VITE_APP_OPEN_PROXY === 'true'
    //       // ? env.value.VITE_APP_PROXY_PREFIX + res.data.pdf_url
    //       // : env.value.VITE_APP_BASE_URL + res.data.pdf_url
    //       // // daShpwloading.value = false
    //       // dpUrl.value.push(fileUrl) 
    //       // daShpwloading.value = true
    //       // setTimeout(() => {
    //       //   daShpwloading.value = false
    //       // },1000)
          
    //       // window.open(fileUrl, '_blank');
    //   }).catch(err => {
    //       daShpwloading.value = false
    //   })
    // })

    
};
const handlepublishLoadSucc = (item)=>{
  Message.success('已确认发布装卸任务！')
  crudRef.value.refresh();
}
const handleXiugai = (e) => {
  tabs.value = e
}
const setSelectedKeys = (val) => {
  keys = val;
};
const handleAddSucc = ()=>{
  addShow.value = false
  crudRef.value.refresh()
}
const handleZhutiaoCel = ()=>{
  onepipeiShow.value = false
  crudRef.value.refresh()
}
const handleShow = () => {
  showUpload.value = false;
}
const handlecaozuoMb = (row) => {  // 打开操作面板
  tabs.value = 'jc'
  czsjData.value = row
  visiblecaozuoSL.value = true
}
// 选择的
const handleSelChange = (res) => {
};
const beforeUpload = () => {
  return true;
};
// 预报单导入成功
const handleSuccess = (res) => {
  if(res.response.code == 200 && res.response.data.length > 0){
    showUpload.value = false;
    showYuji.value = true;
    yujiloading.value = false;
    let _data = res.response.data;
    let arr = [];
    _data.map((v, i) => {
      console.log(v)
      v.id = i + 1;
      if (v.import_status == 0) {
        v.disabled = true;
      } else {
        v.disabled = false;
        arr.push(v.id);
      }
      v.bz_weight = v.bz_weight - 0;
      v.hz_weight = v.hz_weight - 0;
      v.jf_weight = v.jf_weight - 0;
      v.cyr_weight = v.cyr_weight - 0;
      v.number = v.number - 0;
    });
    selectedKeys.value = arr;
    yujiList = _data;
  }else{
    Message.error("数据异常！无数据或格式错误")
  }
  
};
// 成功   导入
const handleYujiSucc = (res) => {
  yujiloading.value = true
  if (selectedKeys.value.length == 0) {
    Message.error("请选择导入的数据");
    yujiloading.value = false
    return true;
  }
  let arr = [];
  yujiList.map((v, i) => {
    selectedKeys.value.map((vv, ii) => {
      if (vv == v.id) {
        arr.push(v);
      }
    });
  });
  predictionManage.importSave(arr).then((res) => {
    if (res.code == 200) {
      showYuji.value = false;
      yujiloading.value = false
      crudRef.value.requestData();
      // crudRefJzx.value.requestData();
      // handleChongGouList()
      return Notification.success("导入成功！");
    }else{
      yujiloading.value = false
    }
  });
};
const handleYujiCel = () => {
  showYuji.value = false;
};
const downFromOther = () => {
  Message.info('请求服务器下载文件中...')
	const data = {page:1,pageSize:10,type:2}
	const download = (url) => request({ url, data, method: 'post', timeout: 60 * 1000, responseType: 'blob' })
  
	download('prediction/manage/downloadTemplate').then(res => {
	  tool.download(res)
	  Message.success('请求成功，文件开始下载')
	}).catch(() => {
	  Message.error('请求服务器错误，下载失败')
	})
};
const handelShowUp = () => {
  showUpload.value = true;
  fileList.value = [];
  selectedKeys.value = [];
};

const handleQueRenFaHuo = () => {
  console.log('确认发货')
  sendHuoShow.value = true
}

const handleLedgerRenWu = () => {
  console.log('下发装卸任务') 
  publishLoadShow.value = true
}

const openTuoyun = (row) =>{
  console.log(row)
  let tuData = JSON.parse(JSON.stringify(row))
  let tuData2 = JSON.parse(JSON.stringify(row))
  // tuData.



  if(tuData.goods_data != null){
        if (typeof tuData.goods_data === 'object' && Array.isArray(tuData.goods_data)) {
          
        } else if (typeof tuData.goods_data === 'object' && !Array.isArray(tuData.goods_data)) {
          tuData.goods_data = [tuData.goods_data];
        }
    }
    if(tuData.goods_data.length == 1){
      tuData.goods_data.push({
            goods_id:'',  
            baozhuang:'',  
            box:'',  
            is_empty:'',
            box_belong:'',
            box_type:'',  
            box_type_id:'',    
            number_yu:'',  
            hz_weight:'',  
            bz_weight:'',  
            jf_weight:'',  
            cyr_weight:'', 
            size:'',
      },{
            goods_id:'',  
            baozhuang:'',  
            box:'',  
            is_empty:'',
            box_belong:'',
            box_type:'',  
            box_type_id:'',    
            number_yu:'',  
            hz_weight:'',  
            bz_weight:'',  
            jf_weight:'',  
            cyr_weight:'', 
            size:'',
      })
    }else if(tuData.goods_data.length == 2){
      tuData.goods_data.push({
        goods_id:'',  
            baozhuang:'',  
            box:'',  
            is_empty:'',
            box_belong:'',
            box_type:'',  
            box_type_id:'',    
            number_yu:'',  
            hz_weight:'',  
            bz_weight:'',  
            jf_weight:'',  
            cyr_weight:'', 
            size:'',
      })
    }
    tuoyunList.value = tuData
		tuoyunShow.value = true
}
const hadnleChangeContract = () => {
  goods_list.value = []
  addObj.value.goods_id = ''
  request({
      url: 'goods/manage/index',
      method: 'get',
      params:{
          pageSize:1000,
      }
  }).then(res => {
      let _data = res.data.items
      _data.map((v,i)=>{
          v.goods_id = v.id
      })
      _data.map((v,i)=>{
        v.keywords = [
          v.name,
          pinyin(v.name,{toneType:'none',pattern:'first'}).split(' ').join(''),
          pinyin(v.name,{toneType:'none',pattern:'first'}).split(' ').join('').toUpperCase()
        ]
      })
      goods_list.value = _data
  })
}

const handleQueRenZhangdan = (row)=>{
  billData.value = row
  showBill.value = true
}
const handleShuaxin = ()=>{
  showPeisong.value = false
  crudRef.value.refresh()
}
const xiafaPeiSong = (row)=>{
  peisongData.value = row
  showPeisong.value = true
}
const handlecopy = (e)=>{
  console.log("复制：",e)
  addData.value = {
      car_type:(e.car_type != "" || e.car_type != null)?e.car_type + '':"",  // 车种
      car_no:(e.car_no != "" || e.car_no != null)?e.car_no + '':"",  // 车号
      
      process_time:tool.dateFormat(
        Math.round(new Date().getTime() / 1000).toString(),
        "yyyy-MM-dd hh:mm:ss"
      ),  // 通知时间
      transport_type:(e.transport_type != "" && e.transport_type != null)?e.transport_type + '':"",  // 运输方式
      service_type:(e.service_type != "" && e.service_type != null)?e.service_type + '':"",  //  服务方式
      shipper:(e.shipper != "" && e.shipper != null)?e.shipper + '':"",   // 托运人
      shipper_agent:(e.shipper_agent != "" && e.shipper_agent != null)?e.shipper_agent + '':"",   // 托运经办人
      shipper_phone:(e.shipper_phone != "" && e.shipper_phone != null)?e.shipper_phone + '':"",   // 托运人电话
      sending_station:(e.sending_station != "" && e.sending_station != null)?e.sending_station - 0:"",   // 发站
      sending_tlj:(e.sending_tlj != "" && e.sending_tlj != null)?e.sending_tlj - 0:"",   // 发 铁路局
      sending_station_special:(e.sending_station_special != "" && e.sending_station_special != null)?e.sending_station_special + '':"",  // 发站专用线
      come_address:(e.come_address != "" && e.come_address != null)?e.come_address - 0:"",   // 到站
      come_tlj:(e.come_tlj != "" && e.come_tlj != null)?e.come_tlj - 0:"",   // 到 铁路局
      arrive_station_special:(e.arrive_station_special != "" && e.arrive_station_special != null)?e.arrive_station_special:'四川威斯腾物流有限公司专用线',  // 到站专用线
      dept_id:(e.dept_id != "" && e.dept_id != null && e.dept_id != 0)?e.dept_id:"",   // 客户
      customer_handler:(e.customer_handler != "" && e.customer_handler != null)?e.customer_handler + '':"",   // 客户经办人
      customer_tel:(e.customer_tel != "" && e.customer_tel != null)?e.customer_tel + '':"",    // 客户电话
      contract_id:(e.contract_id != "" && e.contract_id != null && e.contract_id != 0)?e.contract_id + "":"",   // 合同
      serve_type:(e.serve_type != "" && e.serve_type != null)?e.serve_type + '':"",   // 是否仓储
      shipping:(e.shipping != "" && e.shipping != null)?e.shipping + '':"",   // 配送电话
      shipping_address:(e.shipping_address != "" && e.shipping_address != null)?e.shipping_address + '':"",   // 配送地址
      goods_data:(e.goods_data != "" && e.goods_data != null)?e.goods_data:[]
  }
  addShow.value = true
}
const zhangdanshuaxin = ()=>{
  showBill.value = false
  crudRef.value.refresh();
}
const handleZhangdan = (row)=>{
  tabs.value = 'zd'
  czsjData.value = row
  visiblecaozuoSL.value = true
}

const itemTotal = ref({})

const options = reactive({
  id: 'flyos_send_manage',
  rowSelection: {
    showCheckedAll: true
  },
  pk: 'id',
  operationColumn: true,
  operationWidth: 400,
  operationColumnAlign:'center',
  operationColumnWidth: 300,
  formOption: {
    viewType: 'modal',
    width: 600
  },
  showSummary: true,
  summary: [
      // 定义 amountA 字段加总合计
      {
          dataIndex: 'number',
          action: 'sum'
      },
      {
          dataIndex: 'hz_weight',
          action: 'sum'
      },
      {
          dataIndex: 'bz_weight',
          action: 'sum'
      },
      {
          dataIndex: 'jf_weight',
          action: 'sum'
      },
      {
          dataIndex: 'cyr_weight',
          action: 'sum'
      },
  ],
  api: predictionManage.getList,
  recycleApi: predictionManage.getRecycleList,
  add: {
    show: false,
    api: predictionManage.save,
    text: "新增预报",
    auth: ["prediction:manage:save"],
  },
  edit: {
    show: false,
    api: predictionManage.update,
    auth: ["prediction:manage:update"],
  },
  delete: {
    show: true,
    api: predictionManage.deletes,
    auth: ["prediction:manage:delete"],
    realApi: predictionManage.realDeletes,
    realAuth: ["prediction:manage:realDeletes"],
  },
  recovery: {
    show: false,
    api: predictionManage.recoverys,
    auth: ["prediction:manage:recovery"],
  },
  import: {
    show: false,
    url: "prediction/manage/import",
    templateUrl: "prediction/manage/downloadTemplate",
    auth: ["prediction:manage:import"],
  },
  export: {
    show: true,
    url: "prediction/manage/export",
    auth: ["prediction:manage:export"],
  },
  beforeRequest: (params) => {
    params.prediciont_status = ''
    params.is_hebing = 2
    params.type = 2
    let obj = JSON.parse(JSON.stringify(params))
    obj.is_hebing = ""
    predictionManage.getManageTotal(obj).then(res => {
      itemTotal.value = res.data.total
    })
  },
  afterRequest: (params) => {
    keys = []
    
    
    params.map((v, i) => {
      
      if (v.load_detail == null) {   // 未生成装卸任务
        v.load = 3
      } else if (v.load_detail.detail_load_status == 0) { // 已生成装卸任务
        v.load = 2
      } else if (v.load_detail.detail_load_status == 1) { // 已生成装卸任务 
        v.load = 1 
      }

      if(v.goods_data !== null){
        if (typeof v.goods_data === 'object' && Array.isArray(v.goods_data)) {
            
        } else if (typeof v.goods_data === 'object' && !Array.isArray(v.goods_data)) {
          v.goods_data = [{...v.goods_data}];
        }
      }else{
        v.goods_data = []
      }
      v.number_yu = (v.number_yus - 0);
      v.weight = (v.weight - 0).toFixed(3);
      v.weight_yu = (v.weight_yus - 0).toFixed(3);
      v.yb_weight = (v.yb_weight - 0).toFixed(3);
      v.goods_ids = v.goods_id
      v.bz_weight = (v.bz_weights - 0).toFixed(3)
      v.cyr_weight = (v.cyr_weights - 0).toFixed(3)
      v.hz_weight = (v.hz_weights - 0).toFixed(3)
      v.jf_weight = (v.jf_weights - 0).toFixed(3)
      if(v.pay_order.length == 0){
        v.is_compled = 0
        v.pay_order_price = 0
      }else{
        let num = v.pay_order.findIndex(item=>{
          return item.is_confirm == 0
        })
        if(num != -1){
          v.is_compled = 0
        }else{
          v.is_compled = 1
        }
        let price = 0
        v.pay_order.map((vv,ii)=>{
          price += (vv.pay_real_price - 0)
        })
        v.pay_order_price = price.toFixed(2)
      }
      if (v.prediciont_status == 0 && v.is_nobody == 0 && v.is_compled == 0) {
        v.disabled = false;
      } else {
        v.disabled = true;
      }
    });
  },
  afterDelete:(params)=>{
  	keys = []
  },
  beforeSearch: (params) => {
    console.log('搜索前：', params)
    if (params.goods_ids) {
      params.goods_id = params.goods_ids
    } else {
      params.goods_id = ''
    }
  }
})

const columns = reactive([
  {
    title: "运单号",
    dataIndex: "yundanhao",
    formType: "input",
    search: true,
    addDisplay: false,
    editDisplay: false,
  },
  {
    title: "原票号",
    dataIndex: "ticket_number",
    formType: "input",
    width:180,
    search: true
  },
  {
    title: "车厢号",
    dataIndex: "car_no",
    formType: "input",
    search: true,
    addDisplay: false,
    editDisplay: false,
  },
  {
    title: "运输方式",
    dataIndex: "transport_type",
    formType: "select",
    dict: {
      name: "transport_type",
      props: {
        label: "title",
        value: "key"
      },
      translation: true
    },
    control: (val) => {
          if (val == 1) {
              return {
                box: { display: true },
              }
          }else{
            return {
                box: { display: false },
              }
          }
          
      }
  },
  {
    title: "发站 - 到站",
    dataIndex: "producer",
    formType: "input",
    search: false
  },
  {
    title: "运单状态",
    dataIndex: "prediciont_status",
    formType: "select",
    align: "center",
    search: false,
    addDisplay: false,
    editDisplay: false,
    dict: {
      data(){
          return [
              { label: "未发运", value: 0 },
              { label: "已发运", value: 1 },
          ]
      },
      translation: true,
    },
  },
  {
    title: "客户",
    dataIndex: "dept_id",
    formType: "select",
    search: true,
    width:180,
    dict: {
      // 远程通用接口请求，新版代码生成都有一个 remote 接口
      remote: "system/dept/remote",
      // 指定组件接收的props
      props: { label: "name", value: "id" },
      // 开启分页
      openPage: false,
      // 远程请求配置项
      remoteOption: {
        // 按用户名排序
        sort: { id: "desc" }, // 如果不指定排序方式，默认为正序排序
        // 设置查询的字段
        select: ["id", "name"],
        // 设置数据过滤
        filter: {
          type: ["=", 2],
          status: ['=',1]
        },
        // 关联模型
        relations: [],
      },
      translation: true,
    },
  },
  {
    title: "合同号",
    dataIndex: "contract_no",
    formType: "select",
    width:180,
    search: true
  },
  {
    title: "品名",
    dataIndex: "goods_id",
    formType: "select",
    width:180,
    search: true,
    dict: {
				// 远程通用接口请求，新版代码生成都有一个 remote 接口
				url: "goods/manage/index",
				method:'GET',
				// 指定组件接收的props
				props: { label: "name", value: "id" },
				// 开启分页
				// 远程请求配置项
        params:{
          pageSize:10000
        },
				remoteOption: {
					// 设置查询的字段
					select: ["id", "name"],
					// 关联模型
					relations: [],
				},
        translation: true
		},
    commonRules: {
      required: true,
      message: "请选择品名"
    }
  },
  {
    title: "集装箱",
    dataIndex: "boxs",
    width:180,
    formType: "input",
    display:true,
    addDisplay: false,
    editDisplay: false,
  },
  {
    title: "运单金额",
    dataIndex: "pay_order_price",
    formType: "input",
    display:true,
    addDisplay: false,
    editDisplay: false,
  },
  {
    title: "支付状态",
    dataIndex: "prediction_pay_status",
    formType: "select",
    align: "center",
    search: false,
    addDisplay: false,
    editDisplay: false,
    dict: {
      name: "prediction_pay_status",
      props: {
        label: "title",
        value: "key",
      },
      translation: true,
    },
  },
  {
    title: "服务方式",
    dataIndex: "service_type",
    formType: "select",
    search: true,
    // hide:true,
    
    dict: {
      data(){
          return [
              { label: "站到站", value: 1 },
              { label: "站到门", value: 2 },
              { label: "门到站", value: 3 },
              { label: "门到门", value: 4 },
          ]
      },
      translation: true,
    }
  },
  {
    title: "装车时间",
    dataIndex: "load_time",
    width:180,
    formType: "range",
    addDisplay: false,
    editDisplay: false,
    showTime: true
  },
  {
    title: "办理时间",
    dataIndex: "process_time",
    width:180,
    formType: "range",
    addDisplay: false,
    editDisplay: false,
    showTime: true
  },
  
  {
    title: "数量（件）",
    dataIndex: "number",
    formType: "input",
  },
  {
    title: "货重",
    dataIndex: "hz_weight",
    formType: "input",
  },
  {
    title: "标重",
    dataIndex: "bz_weight",
    formType: "input",
  },
  {
    title: "计费重量",
    dataIndex: "jf_weight",
    formType: "input",
  },
  {
    title: "承运人重量",
    dataIndex: "cyr_weight",
    formType: "input",
  },
  {
    title: "发运时间",
    dataIndex: "send_time",
    width:180,
    formType: "range",
    search: true,
    sortable: {
      sortDirections: ["ascend", "descend"],
      sorter: true,
    },
    showTime: true
  },
  {
    title: "创建时间",
    dataIndex: "created_at",
    width:180,
    formType: "range",
    align: "center",
    search: true,
    addDisplay: false,
    editDisplay: false,
    sortable: {
      sortDirections: ["ascend", "descend"],
      sorter: true,
    },
    showTime: true,
  },
])
const columnsEpor = reactive([
  
  {
    title: "客户名称",
    dataIndex: "dept_name",
    align: "center",
    ellipsis: true,
    fixed: "left",
    width:180,
    tooltip: true,
  },
  
  {
    title: "办理时间",
    dataIndex: "process_time",
    align: "center",
    ellipsis: true,
    width:180,
    tooltip: true,
  },
  {
    title: "原票号",
    dataIndex: "ticket_number",
    align: "center",
    ellipsis: true,
    width:140,
    tooltip: true,
  },
  {
    title: "车种",
    dataIndex: "car_type",
    align: "center",
    ellipsis: true,
    width:100,
    tooltip: true,
  },
  {
    title: "车号",
    dataIndex: "car_no",
    align: "center",
    ellipsis: true,
    width:100,
    tooltip: true,
  },
  {
    title: "箱号",
    dataIndex: "box",
    align: "center",
    ellipsis: true,
    width:100,
    tooltip: true,
  },
  {
    title: "箱型箱类",
    dataIndex: "box_type",
    align: "center",
    ellipsis: true,
    width:140,
    tooltip: true,
  },
  {
    title: "空重状态",
    dataIndex: "is_empty",
    align: "center",
    ellipsis: true,
    tooltip: true,
    width:100,
    slotName: 'is_empty',
  },
  {
    title: "箱属",
    dataIndex: "box_belong",
    align: "center",
    ellipsis: true,
    width:100,
    tooltip: true,
  },
  {
    title: "运输方式",
    dataIndex: "transport_type",
    align: "center",
    ellipsis: true,
    tooltip: true,
    width:100,
    slotName: 'transport_type',
  },
  {
    title: "发站",
    dataIndex: "sending_station",
    align: "center",
    ellipsis: true,
    width:100,
    tooltip: true,
    slotName: 'sending_station',
  },
  {
    title: "到站",
    dataIndex: "come_address",
    align: "center",
    ellipsis: true,
    width:100,
    tooltip: true,
    slotName: 'come_address',
  },
  {
    title: "品名",
    dataIndex: "goods_name",
    align: "center",
    ellipsis: true,
    width:140,
    tooltip: true,
  },
  {
    title: "件数",
    dataIndex: "number",
    align: "center",
    ellipsis: true,
    width:100,
    tooltip: true,
  },
  {
    title: "标重(吨)",
    dataIndex: "bz_weight",
    align: "center",
    ellipsis: true,
    width:100,
    tooltip: true,
  },
  {
    title: "货重(吨)",
    dataIndex: "hz_weight",
    align: "center",
    ellipsis: true,
    width:100,
    tooltip: true,
  },
  {
    title: "计费重量(吨)",
    dataIndex: "jf_weight",
    align: "center",
    ellipsis: true,
    width:100,
    tooltip: true,
  },
  {
    title: "承运人重量(吨)",
    dataIndex: "cyr_weight",
    align: "center",
    ellipsis: true,
    tooltip: true,
    width:140,
  },
  {
    title: "合同号",
    dataIndex: "contract_no",
    align: "center",
    ellipsis: true,
    width:140,
    tooltip: true,
    slotName: 'contract_id',
  },
  {
    title: "服务方式",
    dataIndex: "service_type",
    align: "center",
    ellipsis: true,
    width:100,
    tooltip: true,
    slotName: 'service_type',
  },
  {
    title: "收货人",
    dataIndex: "shipper",
    align: "center",
    width:100,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "收货经办人",
    dataIndex: "shipper_agent",
    align: "center",
    width:100,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "收货电话",
    dataIndex: "shipper_phone",
    align: "center",
    ellipsis: true,
    width:100,
    tooltip: true,
  },
  {
    title: "发站专用线",
    dataIndex: "sending_station_special",
    align: "center",
    ellipsis: true,
    width:100,
    tooltip: true,
  },
  {
    title: "包装",
    dataIndex: "baozhuang",
    align: "center",
    ellipsis: true,
    width:100,
    tooltip: true,
  },
  {
    title: "体积",
    dataIndex: "size",
    align: "center",
    ellipsis: true,
    width:100,
    tooltip: true,
  },
  {
    title: "备注",
    dataIndex: "remark",
    align: "center",
    ellipsis: true,
    fixed: "right",
    width:180,
    tooltip: true,
    cellStyle:{color:'red'}
  },
]);
const sendList = ref([])
onMounted(() => {
  commonApi.getDict("transport_type").then((res) => {
    yunshuList.value = res.data;
  });
  commonApi.getDict("serve_type").then((res) => {
    fuwuList.value = res.data;
  });
  request({
      url: 'prediction/dfz/index',
      method: 'get',
      params: {
          pageSize: 1000,
      }
  }).then(res => {
      sendList.value = res.data.items
  });
  handleDeptList();
  hadnleChangeContract()
});
</script>
<script> export default { name: 'send:manage' } </script>